# -*- coding: utf-8 -*-
"""
 ----------------------------------------
|File Name:     PageObjectTest
|Author:        WYT
|date:          2021/6/30
 ----------------------------------------
|  Change Activity:
|                   2021/6/30:
-----------------------------------------
"""
from lxml import etree

from PageObjectRequests import base_url
from base.BaseMethod import BM
from settings import log_path
from util import http_utils
from util.DataQuery.DbTools import DbTools
from util.DataQuery.FormDataDecorator import FormDataDecorator
from util.Logger import Logger
from util.g import g
from util.pdfSplit.compress_pdf import CompressPdf
from util.pdfSplit.pdf_split import get_file_oss
from util.selenium.webdriver.common.by import By
from util.sys_dict import transWay, staType, staSource, transResult


class IAStaDesc():
    parent_btn_loc = (By.LINK_TEXT, "企业创新能力")
    form_btn_loc = (By.LINK_TEXT, "科技成果转化情况")

    def __init__(self, response, driver=None, text=""):
        self.driver = driver
        self.text = text
        self.response = response
        self.size = 2
        self.flag = False
        setattr(g, self.class_name, list())

    @property
    def class_name(self):
        return self.__class__.__name__

    #  这里把 填写 textarea 和 添加数据 方法分离。 WriteInnovationAbilityForm 实例化该对象时，需要调用两个方法。
    def fill_form(self):
        res_text = self.response.get("text")
        res_tree = etree.HTML(res_text)
        detail_url = BM.get_first(res_tree.xpath("//ul[@id='title']/li[2]/a/@href"))
        type_res = BM.get_first(res_tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataEprCycxForm_type']/@value"))
        if not detail_url:
            return False
        detail_url = detail_url if detail_url.startswith("https://") else \
            base_url + (detail_url if detail_url.startswith("/") else "/" + detail_url)
        res = http_utils.send_get(detail_url)
        add_url = "https://slb.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/saveOrUpdateDataEprCycx.do"
        data = {
            "dataeprcycx.id": "",
            "dataInnocom.id": "",
            "dataEprCycx.dataId": "",
            "dataEprCycx.entId": "",
            "subType": "",
            "type": "",
            "struts.token.name": "token",
            "token": res.get("token"),
            "dataEprCycx.createDate": "",
            "dataEprCycx.Ckjcgzh": self.text,
        }
        text = res.get("text")
        tree = etree.HTML(text)
        cycx_id_res = BM.get_first(tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataEprCycx.id']/@value"))
        id_res = BM.get_first(tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataInnocom.id']/@value"))
        dataId_res = BM.get_first(tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataEprCycx.dataId']/@value"))
        entId_res = BM.get_first(tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataEprCycx.entId']/@value"))
        subType_res = BM.get_first(
            tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataEprCycxForm_subType']/@value"))
        createDate_res = BM.get_first(
            tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataEprCycxForm_dataEprCycx_createDate']/@value"))
        data["dataeprcycx.id"] = cycx_id_res
        data["dataInnocom.id"] = id_res
        data["dataEprCycx.dataId"] = dataId_res
        data["dataEprCycx.entId"] = entId_res
        data["subType"] = subType_res
        data["type"] = type_res
        data["dataEprCycx.createDate"] = createDate_res

        res = http_utils.send_post(add_url, data=data)
        message = res.get("message")
        g.logger.info("科技成果转化情况 上传结果: {}".format(message))
        if u"成功" in message:
            return True
        else:
            return False

    @FormDataDecorator
    def ia_sta_desc(self, id="", sta_name="", sta_type="", sta_source="", trans_result="", trans_date="", sort_num='', ipr_ids="", ipn_ids="", rd_ids="", ps_ids="", trans_ids="", oss_path=None):
        try:
            save_url = "https://slb.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/saveOrUpdateDataEprTrans.do"
            data = {
                "dataEprTrans.id": "",
                "dataInnocom.id": "",
                "subType": "1",
                "dataEprTrans.dataId": "",
                "dataId": "",
                "struts.token.name": "token",
                # "token": token,
                "dataEprTrans.transName": sta_name,
                "dataEprTrans.transType": staType.get(sta_type),
                "dataEprTrans.transSource": staSource.get(sta_source),
                "dataEprTrans.transResult": transResult.get(trans_result),
                "dataEprTrans.transYear": str(trans_date),
                # 排序号
                "dataEprTrans.position": str(sort_num),
                "dataEprTrans.transIp": ",".join([]),
                "__multiselect_dataEprTrans.transIp": "",
                "dataEprTrans.transRd": ",".join([]),
                "__multiselect_dataEprTrans.transRd": "",
                "dataEprTrans.transPs": ",".join([]),
                "__multiselect_dataEprTrans.transPs": "",
                "dataEprTrans.transWay": ",".join([]),
                "__multiselect_dataEprTrans.transWay": ""
                # 附件
                # "upload: (binary)",
            }
            ipr_value = []
            if ipr_ids:
                if "0" in ipr_ids.split(","):
                    ipr_value.append("其他")
                #  先从数据库里面查一下 ipr_ids 对应的 ip 是不是都有
                ipr_sql = """
                select * from hitech.ent_res_ipr where co_id={} and year={} and ipr_id in ({})
                """.format(g.co_id, g.year, ipr_ids)
                ipr_data = DbTools.get_hitech_record_by_sql(ipr_sql, model="all")
                ipr_ids = ",".join([str(i.get("ipr_id")) for i in ipr_data])
                for i in ipr_ids.split(","):
                    if i == "":
                        continue
                    if i == "0":
                        if u"其他" not in ipr_value:
                            ipr_value.append("其他")
                        ipr_value.append("其他")
                        continue
                    if i.isdigit():
                        ipr_value.append("IP" + i.zfill(2))
            if ipn_ids:
                if "0" in ipn_ids.split(","):
                    if u"其他" not in ipr_value:
                        ipr_value.append("其他")
                ipn_sql = """
                select * from hitech.ent_res_ipn where co_id={} and year={} and ipr_id in ({})
                """.format(g.co_id, g.year, ipn_ids)
                ipn_data = DbTools.get_hitech_record_by_sql(ipn_sql, model="all")
                ipn_ids = ",".join([str(i.get("ipr_id")) for i in ipn_data])
                for n in ipn_ids.split(","):
                    if n == "":
                        continue
                    if n == "0":
                        if u"其他" not in ipr_value:
                            ipr_value.append("其他")
                        continue
                    if n.isdigit():
                        nstr = "NIP" + n.zfill(2)
                        ipr_value.append(nstr)
            data["dataEprTrans.transIp"] = ",".join(ipr_value)

            if rd_ids:
                rd_value = []
                if "0" in rd_ids.split(","):
                    rd_value.append("其他")
                rd_sql = """
                select * from hitech.ent_res_rd where co_id={} and year={} and rd_id in ({})
                """.format(g.co_id, g.year, rd_ids)
                rd_data = DbTools.get_hitech_record_by_sql(rd_sql, model="all")
                rd_ids = ",".join([str(i.get("rd_id")) for i in rd_data])
                for i in rd_ids.split(","):
                    if i == "":
                        continue
                    if i == "0":
                        if u"其他" not in rd_value:
                            rd_value.append("其他")
                    if i.isdigit():
                        rd_value.append("RD" + i.zfill(2))
                data["dataEprTrans.transRd"] = ",".join(rd_value)

            # 获取 产品服务关联列表
            if ps_ids:
                ps_value = []
                if "0" in ps_ids.split(","):
                    ps_value.append("其他")
                ps_sql = """
                select * from hitech.ent_res_ps where co_id={} and year={} and ps_id in ({})
                """.format(g.co_id, g.year, ps_ids)
                ps_data = DbTools.get_hitech_record_by_sql(ps_sql, model="all")
                ps_ids = ",".join([str(i.get("ps_id")) for i in ps_data])
                for i in ps_ids.split(","):
                    if i == "":
                        continue
                    if i == "0":
                        if u"其他" not in ps_value:
                            ps_value.append("其他")
                    if i.isdigit():
                        ps_value.append("PS" + i.zfill(2))
                data["dataEprTrans.transPs"] = ",".join(ps_value)

            if trans_ids:
                trans_way = []
                for i in trans_ids.split("#"):
                    trans_way.append(transWay.get(i))
                data["dataEprTrans.transWay"] = ",".join(trans_way)


            file_path = None
            if g.need_file:
                if oss_path:
                    file_path = BM.get_material_path() + "\\STA\\sta_{}.pdf".format(id)
                    is_exist = BM.check_file(file_path=file_path, size=self.size)
                    if is_exist is True:
                        oss_file = get_file_oss(oss_path=oss_path, local_path=file_path + ".pdf")
                        BM.wait_file(file_path=oss_file)
                        CompressPdf(file_path=oss_file, max_size=self.size).compress()
                        BM.wait_file(file_path=file_path)

            print(data)

        except Exception as err:
            msg = "error: {} file: {} lines: {}".format(err,
                                                        err.__traceback__.tb_frame.f_globals[
                                                            "__file__"],
                                                        err.__traceback__.tb_lineno)
            g.logger.error(msg)
            raise Exception(msg)

if __name__ == '__main__':
    g.logger = Logger(log_file_name=log_path.replace("log.txt", "test_request.log"), log_level=Logger.DEBUG,
                      logger_name="test_request").get_log()
    g.need_file = False
    g.co_id = 115576
    g.year = 2021
    IAStaDesc("", "", "").ia_sta_desc()
    pass
